package com.kk.xhr.admin.mail;

import com.kk.xhr.admin.util.MailUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 邮箱服务接口
 *
 * @author kkmystery
 * @version 1.0 2021/3/30
 * @since 1.0.0
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MailService {
    private final Executor messageExecutor;
    private final JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送简单邮件
     *
     * @param to      发送对象
     * @param subject 标题
     * @param content 内容
     * @throws MessagingException
     */
    public void sendSimpleMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        // 标题
        helper.setSubject(subject);
        // 内容
        helper.setText(content, true);
        mailSender.send(message);
    }

    /**
     * 批量发送
     *
     * @param emails 工资账单
     * @throws MessagingException
     */
    public void batchSendSimpleMail(List<SalaryEmail> emails) {
        MimeMessage message = mailSender.createMimeMessage();
        emails.forEach(salary -> {
            // 线程池来执行
            CompletableFuture.runAsync(() -> {
                try {
                    MimeMessageHelper helper = new MimeMessageHelper(message, true);
                    helper.setFrom(from);
                    helper.setTo(salary.getTo());
                    // 标题
                    helper.setSubject(salary.getSubject());
                    // 内容
                    helper.setText(MailUtil.generateSalaryTable(salary.getSalary(), salary.getName()), true);
                    mailSender.send(message);
                } catch (MessagingException e) {
                    log.info("send mail service fail...");
                }
            }, messageExecutor);
        });

    }
}
